package com.pamakids.umsocial;

import java.io.File;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.umeng.socialize.bean.RequestType;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.TencentWBSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.sso.UMTencentSsoHandler;
import com.umeng.socialize.utils.OauthHelper;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

/**
 * Created by Administrator on 2015/1/6.
 */
public class DoOauthActivity extends Activity {

    public static final String TAG = "DoOauthActivity";

    public static final String METHOD_LOGIN = "method_login";
    public static final String METHOD_CANCEL = "method_cancle";
    public static final String METHOD_SHARE = "method_share";

    private UMSocialService mController = null;
    private Intent intent = null;

    @Override
    protected void onCreate(Bundle savedInstanceState){

        Log.d(TAG, "DoOauthActivity --> onCreate");
        super.onCreate(savedInstanceState);

        mController = UMServiceFactory.getUMSocialService("com.umeng.login", RequestType.SOCIAL);
        intent = getIntent();
        String method = intent.getStringExtra("method");
        String platform = intent.getStringExtra("platform");
        SHARE_MEDIA share_media = Platform.checkShareMedia(platform);

        if (method.equals(METHOD_LOGIN))           //判断是否已获取相关授权，若是则直接调用catchPlatformInfo,否则申请授权成功后调用catchPlatformInfo
        {
            Log.d(TAG, "DoOauthActivity --> 登录，开始验证是否已对平台授权！Platform = " + platform);
            if(OauthHelper.isAuthenticated(DoOauthActivity.this, share_media)) {
                catchPlatformInfo(share_media);
            } else {
                doOauthVerify(share_media);
            }
        }
        else if (method.equals(METHOD_CANCEL))       //判断是否已取得授权，若已取得授权则清空授权，否则无需做操作
        {
            if(OauthHelper.isAuthenticated(DoOauthActivity.this, share_media)) {
                deleteOauth(share_media);
            }
        }
        else if (method.equals(METHOD_SHARE))       //判断是否已取得授权，已取得授权则直接分享，否则获取授权后分享
        {
            if(OauthHelper.isAuthenticated(DoOauthActivity.this, share_media))
                shareHandler(share_media);
            else
                doOauthVerify(share_media);
        }
    }

    /**获取授权*/
    private void doOauthVerify(SHARE_MEDIA share_media){

        Log.d(TAG, "开始授权！");
        if(share_media.equals(SHARE_MEDIA.QQ))
        {
            Log.d(TAG, "开始QQ平台授权！");
            String qqAppid = intent.getStringExtra("qqAppid");
            String qqAppkey = intent.getStringExtra("qqAppkey");
            UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, qqAppid, qqAppkey);
            qqSsoHandler.addToSocialSDK();
        }
        else if(share_media.equals(SHARE_MEDIA.QZONE))
        {
        	Log.d(TAG, "开始QQ空间授权！");
        	String qqAppid = intent.getStringExtra("qqAppid");
            String qqAppkey = intent.getStringExtra("qqAppkey");
            QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, qqAppid, qqAppkey);
            qZoneSsoHandler.addToSocialSDK();
        }
        else if(share_media.equals(SHARE_MEDIA.TENCENT))
        {
        	Log.d(TAG, "开始腾通微博授权");
            TencentWBSsoHandler tencent = new TencentWBSsoHandler();
            tencent.addToSocialSDK();
            mController.getConfig().setSsoHandler(tencent);
        }
        else if(share_media.equals(SHARE_MEDIA.WEIXIN) || share_media.equals(SHARE_MEDIA.WEIXIN_CIRCLE))
        {
            Log.d(TAG, "开始微信平台授权！");
            String wechatAppID = intent.getStringExtra("wechatAppID");
            String wechatAppSecret = intent.getStringExtra("wechatAppSecret");

            UMWXHandler wxHandler = new UMWXHandler(this, wechatAppID, wechatAppSecret);
            wxHandler.addToSocialSDK();
            
            UMWXHandler circleHanddler = new UMWXHandler(this, wechatAppID, wechatAppSecret);
            circleHanddler.setToCircle(true);
            circleHanddler.addToSocialSDK();
        }
        else if(share_media.equals(SHARE_MEDIA.SINA))
        {
            Log.d(TAG, "开始新浪平台授权！");
            SinaSsoHandler sina = new SinaSsoHandler();
            sina.addToSocialSDK();
            mController.getConfig().setSsoHandler(sina);
        }
        
        mController.doOauthVerify(DoOauthActivity.this, share_media, new SocializeListeners.UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                Log.d(TAG, "doOauthVerify --> onStart");
            }

            @Override
            public void onComplete(Bundle bundle, SHARE_MEDIA share_media) {
                Log.d(TAG, "doOauthVerify --> onComplete");
                //判断授权是否成功
                if (bundle != null && !TextUtils.isEmpty(bundle.getString("uid"))) {
                    Log.d(TAG, "平台授权成功！uid = " + bundle.getString("uid"));

                    String method = intent.getStringExtra("method");
                    if (method.equals(METHOD_LOGIN))            //获取平台信息
                        catchPlatformInfo(share_media);
                    else            //分享
                        shareHandler(share_media);
                } else {
                    Log.d(TAG, "授权失败！");
                    finish();
                }
            }

            @Override
            public void onError(SocializeException e, SHARE_MEDIA share_media) {
                Log.d(TAG, "doOauthVerify --> onError");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                Log.d(TAG, "doOauthVerify --> onCancel");
                finish();
            }
        });
    }
    

	private void deleteOauth(SHARE_MEDIA share_media){

        Log.d(TAG, "deleteOauth called!");

        mController.deleteOauth(DoOauthActivity.this, share_media, new SocializeListeners.SocializeClientListener() {
            @Override
            public void onStart() {
                Log.d(TAG, "deleteOauth --> onStart!");
            }

            @Override
            public void onComplete(int status, SocializeEntity socializeEntity) {

                Log.d(TAG, "deleteOauth --> onComplete!");

                if (status == 200) {
                    Log.d(TAG, "删除成功！");
                    UMSocialContext.getInstance().dispatchStatusEventAsync("CancelAuthResult", String.valueOf(status));
                } else {
                    Log.d(TAG, "删除失败！");
                }

                finish();
            }
        });
    }

    /**获取平台信息*/
    private void catchPlatformInfo(SHARE_MEDIA share_media) {

        Log.d(TAG, "catchPlatformInfo called!");

        mController.getPlatformInfo(DoOauthActivity.this, share_media, new SocializeListeners.UMDataListener() {

            @Override
            public void onStart() {
                Log.d(TAG, "获取平台用户信息开始！");
            }

            @Override
            public void onComplete(int status, Map<String, Object> info) {

                Log.d(TAG, "catchPlatformInfo --> onComplete!");

                if( status == 200 && info != null )
                {
                    Log.d(TAG, "获取用户数据成功！");
                    UMSocialContext.getInstance().dispatchStatusEventAsync("AuthResult", info.toString());
                }
                else
                {
                    Log.d(TAG, "获取用户数据失败，status = " + status);
                }

                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.d( TAG, "DoOauthActivity --> onActivityResult" );
        Log.d(TAG, "requestCode = " + requestCode);
        Log.d(TAG, "resultCode = " + resultCode);

        super.onActivityResult(requestCode, resultCode, data);

        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode) ;

        Log.d(TAG, "ssoHandler = " + ssoHandler);

        if(ssoHandler != null){
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    /**分享方法*/
    private void shareHandler(SHARE_MEDIA share_media){

//        String id = intent.getStringExtra("id");
        String shareText = intent.getStringExtra("shareText");
        String imageURL = intent.getStringExtra("imageUrl");
        String title = intent.getStringExtra("title");
        String targetUrl = intent.getStringExtra("targetUrl");


        UMImage umImage = null;
        if(imageURL != null && imageURL.length() != 0)
        {
            if(imageURL.contains("http:"))        //参数路径为网络路径
            {
                Log.d( TAG, "分享网络图片： imageURL = " + imageURL );
                umImage = new UMImage(DoOauthActivity.this, imageURL);
            }
            else                                        //参数路径为本地绝对路径
            {
                Log.d( TAG, "分享本地图片： imageURL = " + imageURL );
                umImage = new UMImage(DoOauthActivity.this, new File(imageURL));
            }
            umImage.setTargetUrl(targetUrl);
            umImage.setTitle(title);
        }
        else
        {
            Log.d(TAG, "无分享图片！");
        }

        if (share_media.equals(SHARE_MEDIA.WEIXIN))
        {
            WeiXinShareContent weixinContent = new WeiXinShareContent();
            weixinContent.setShareContent(shareText);
            weixinContent.setTitle(title);
            weixinContent.setTargetUrl(targetUrl);
            weixinContent.setShareImage(umImage);
            mController.setShareMedia(weixinContent);
        }
        else if (share_media.equals(SHARE_MEDIA.WEIXIN_CIRCLE))
        {
            CircleShareContent circleMedia = new CircleShareContent();
            circleMedia.setShareContent(shareText);
            circleMedia.setTitle(title);
            circleMedia.setShareImage(umImage);
            circleMedia.setTargetUrl(targetUrl);
            mController.setShareMedia(circleMedia);
        }
        else if (share_media.equals(SHARE_MEDIA.QQ))
        {
            QQShareContent qqShareContent = new QQShareContent();
            qqShareContent.setShareContent(shareText);
            qqShareContent.setTitle(title);
            qqShareContent.setShareImage(umImage);
            qqShareContent.setTargetUrl(targetUrl);
            mController.setShareMedia(qqShareContent);
        }
        else if (share_media.equals(SHARE_MEDIA.QZONE))
        {
            QZoneShareContent qzone = new QZoneShareContent();
            qzone.setShareContent(shareText);
            qzone.setTargetUrl(targetUrl);
            qzone.setTitle(title);
            qzone.setShareImage(umImage);
            mController.setShareMedia(qzone);
        }
        else if (share_media.equals(SHARE_MEDIA.SINA))
        {
            SinaShareContent sinaShareContent = new SinaShareContent();
            sinaShareContent.setShareImage(umImage);
            sinaShareContent.setShareContent(shareText);
            sinaShareContent.setTitle(title);
            sinaShareContent.setAppWebSite(targetUrl);
            sinaShareContent.setTargetUrl(targetUrl);
            mController.setShareMedia(sinaShareContent);
        }
        else
        {
            mController.setShareContent(shareText);
            mController.setAppWebSite(share_media, targetUrl);
            mController.setShareImage(umImage);
        }

        mController.directShare(DoOauthActivity.this, share_media, new SocializeListeners.SnsPostListener() {
            @Override
            public void onStart() {
                Log.d(TAG, "开始分享！");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, SocializeEntity socializeEntity) {
                if(i == 200)
                {
                    Log.d(TAG, "分享成功！");
                    UMSocialContext.getInstance().dispatchStatusEventAsync("shared", String.valueOf(i));
                }
                else
                {
                    Log.d(TAG, "分享失败！ errorCode = " + String.valueOf(i));
                }
                Log.d(TAG, "分享完成，调用ShareActivity-->finish");
                finish();
            }
        });
    }
}
